/* 
 * File:   Visualization.cpp
 * Author: cjjonker
 * 
 * Created on 20 december 2012, 15:03
 */

#include "Visualization.h"
#include "GL/gl.h"

Visualization::Visualization() 
{
    // ORDER MATTERS HERE!!! They are drawn on top of eachother. Last one is on top.
    d_visualizers = {&d_smoke, &d_glyphs, &d_streamlines};
}


void Visualization::setSimulation(Simulation* sim)
{
    d_simulation = sim;
    for (auto it = d_visualizers.begin(); it != d_visualizers.end(); ++it)
    {
        (*it)->setSimulation(sim);
        (*it)->setCurrentMapDataset();
        (*it)->setCurrentAlphaDataset();
    }
    
}

void Visualization::visualize(float winW, float winH, int levels, int slice_dt, float alpha)
{
    for (auto it = d_visualizers.begin(); it != d_visualizers.end(); ++it)
    {
        (*it)->setColormapMinMax(levels, slice_dt);
        (*it)->setGlobalAlpha(alpha);
    }
    
    float z = winH / 2;
    
    // visualizers have lower left corner as origin
    glTranslatef(-winW / 2.0, -winH / 2.0, -z);
    
    
    // start to draw at the back because of alpha blending
    
    float dH = levels > 1 ? float(winH) / (levels - 1) : 0.0;    
    
    glPushMatrix();
    for (auto it = d_visualizers.begin(); it != d_visualizers.end(); ++it)    
        if ((*it)->isActive())
        {            
            (*it)->draw(winW, winH, (levels - 1)*slice_dt, levels, slice_dt);
            glTranslatef(0.0, 0.0, winH / 100.0f);
        }
    glPopMatrix();
    
    
    for (int i = (levels - 2); i != -1; --i)
    {     
        glTranslatef(0.0, 0.0, dH);     
        glPushMatrix();
        for (auto it = d_visualizers.begin(); it != d_visualizers.end(); ++it)    
            if ((*it)->isActive())        
            {
                (*it)->draw(winW, winH, (i*slice_dt), levels, slice_dt);
                glTranslatef(0.0, 0.0, winH / 100.0f);
            }
        glPopMatrix();
    }
    
    
    glPushMatrix();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0, float(winW), 0, float(winH), -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    float xpos = 0.0;    

    for (int idx = 0; idx != d_visualizers.size(); ++idx)    
        if (d_visualizers[idx]->isActive())
        {
            d_visualizers[idx]->drawLegend(xpos , 0.0, winW, winH, d_simulation->getDim());    
            xpos += 5.0;
        }
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glPopMatrix();    

}

